package com.qunar.paydata.platform.controller.worksheet;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qunar.paydata.platform.common.entity.ResultEntity;
import com.qunar.paydata.platform.common.param.PageParam;
import com.qunar.paydata.platform.common.util.ExcelUtil;
import com.qunar.paydata.platform.common.util.QunarDateUtil;
import com.qunar.paydata.platform.entity.co.ChartRandomNum;
import com.qunar.paydata.platform.entity.co.WorksheetBaseCo;
import com.qunar.paydata.platform.entity.co.WorksheetChartCountCo;
import com.qunar.paydata.platform.entity.worksheet.WorksheetBase;
import com.qunar.paydata.platform.entity.worksheet.WorksheetDetail;
import com.qunar.paydata.platform.service.co.WorkSheetCoService;
import com.qunar.paydata.platform.service.worksheet.WorksheetService;

/**
 * 
 * @author leonyang.liu
 * @param <V>
 * @param <K>
 * @param <E>
 *
 */
@Controller
@RequestMapping("/workbase")
public class WorkSheetController<V, K, E> {
	
	private static Logger logger = LoggerFactory.getLogger(WorkSheetController.class);
	@Autowired
	private WorksheetService worksheetService;
	
	@Autowired
	private WorkSheetCoService worksheetCoService;

	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException
	 * @comment 查询工单基本信息
	 */
	@RequestMapping("/searchbase")
	public String searchWorkBase(HttpServletRequest request,
			HttpServletResponse response) throws UnsupportedEncodingException {
		request.setAttribute("data", "admin");
		return "/worksheet/tablebase";
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @comment 生成工单报表
	 */
	@RequestMapping("/reportgenerate")
	public String reportGenerateBase(HttpServletRequest request,
			HttpServletResponse response) {
		return "/worksheet/reportgenerate";
	}

	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @comment 生成日报报表
	 */
	@RequestMapping("/dailyreportgenerate")
	public String dailyReportGenerateBase(HttpServletRequest request,
			HttpServletResponse response) {
		return "/worksheet/dayreportgenerate";
	}

	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @comment 生成日报的报表图片
	 */
	@RequestMapping(value = "/generatwschart", method = RequestMethod.GET)
	@ResponseBody
	public ResultEntity<ChartRandomNum> generateWSChart(HttpServletRequest request,
			HttpServletResponse response,HttpSession session) {
		logger.info("------开始生成报表图片------");
		//获取查询条件
		Map<String, Object> fetchWSChartCondition = fetchWSChartCondition(request);
		//调用service生成报表图片
		String wsChartCount = worksheetCoService.getWSChartCount(fetchWSChartCondition,session);
		//两张图表的区分（用两个随机数）
		String random_1 = wsChartCount.split("_")[0];
		String random_2 = wsChartCount.split("_")[1];
		ChartRandomNum chartRandomNum = new ChartRandomNum();
		chartRandomNum.setRandom_1(random_1);
		chartRandomNum.setRandom_2(random_2);
		return new ResultEntity<ChartRandomNum>(0, "成功",
				chartRandomNum);
	}
	@RequestMapping(value = "/insinglebase", method = RequestMethod.GET)
	@ResponseBody
	public String saveSingleBase(HttpServletRequest request,
			HttpServletResponse response) {
		// 获取前台工单数据对象
		WorksheetBase worksheetBase = fetchWorksheetBase(request);
		// 调用dao服务进行数据录入
		int insert = worksheetService.insert(worksheetBase);
		return "" + insert;
	}

	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @comment 查询工单基本数据
	 * 
	 */

	@RequestMapping(value = "/secworksheetbase", method = RequestMethod.GET)
	@ResponseBody
	public ResultEntity<Map<String,Object>> secWorkSheetBase(
			HttpServletRequest request, HttpServletResponse response) {
		// 一、获取基本信息
		String beginDate = request.getParameter("beginDate");
		String endDate = request.getParameter("endDate");
		String worksheet_type = request.getParameter("secWsType");
		String ws_type_detail = request.getParameter("secWsDetail");
		String business_type = request.getParameter("secTradeType");
		String deal_person  = request.getParameter("secDealPerson");
		String job_num  = request.getParameter("secWsNum");
		String is_ws_commont =	request.getParameter("secIsWscommont");
		//分页信息
		String pageNum = request.getParameter("pageNum");
		String pageSize = request.getParameter("pageSize");
		PageParam page = new PageParam(pageNum, pageSize);
		Map<String,Object> queryMap = page.getPageMap();
		queryMap.put("beginDate", beginDate);
		queryMap.put("endDate", endDate);
		queryMap.put("worksheet_type", worksheet_type);
		queryMap.put("ws_type_detail", ws_type_detail);
		queryMap.put("business_type", business_type);
		queryMap.put("deal_person", deal_person);
		queryMap.put("job_num", job_num);
		queryMap.put("is_ws_commont", is_ws_commont);
		List<WorksheetBaseCo> list = worksheetCoService.getWorkSheetBoList(queryMap);
		//获取总数
		int totalCount = worksheetService.selectChartByCondition(queryMap);
		
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("pageNum", page.getPageNum());
		resultMap.put("pageSize", page.getPageSize());
		resultMap.put("data", list);
		resultMap.put("totalCount", totalCount);
		return new ResultEntity<Map<String,Object>>(0, "成功", resultMap);
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @comment 查询工单表格数据（用于报表）
	 * 
	 */

	@RequestMapping(value = "/secworksheetchart", method = RequestMethod.GET)
	@ResponseBody
	public ResultEntity<WorksheetChartCountCo> secWorksheetChart(
			HttpServletRequest request, HttpServletResponse response) {
		// 一、获取查询条件基本信息
		Map<String, Object> fetchSecChartCondition = fetchSecChartCondition(request);
		// 二、调用service服务进行查询
		return new ResultEntity<WorksheetChartCountCo>(0, "成功",
				worksheetCoService.getWorksheetChartCount(fetchSecChartCondition));
	}

	/**
	 * excel表导出
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/exportexcel", method = RequestMethod.GET)
	@ResponseBody
	public String expExcel(HttpServletRequest request,
			HttpServletResponse response) {

		return "正常导出";
	}

	
	@RequestMapping(value = "/secwsdetail", method = RequestMethod.GET)
	@ResponseBody
	public ResultEntity<List<WorksheetDetail>> secWsDetail(HttpServletRequest request,HttpServletResponse response){
		//获取工单类型值
		String ws_type = request.getParameter("ws_type");
		//获取对应的工单细分结果集
		List<WorksheetDetail> wsDetailList = new ArrayList<WorksheetDetail>();
		WorksheetDetail worksheetDetail_1 = new WorksheetDetail();
		WorksheetDetail worksheetDetail_2 = new WorksheetDetail();
		WorksheetDetail worksheetDetail_3 = new WorksheetDetail();
		WorksheetDetail worksheetDetail_4 = new WorksheetDetail();
		WorksheetDetail worksheetDetail_5 = new WorksheetDetail();
		WorksheetDetail worksheetDetail_6 = new WorksheetDetail();
		WorksheetDetail worksheetDetail_7 = new WorksheetDetail();
		WorksheetDetail worksheetDetail_8 = new WorksheetDetail();
		WorksheetDetail worksheetDetail_9 = new WorksheetDetail();
		WorksheetDetail worksheetDetail_10 = new WorksheetDetail();
		switch (Integer.parseInt(ws_type)) {
		case 0:
			worksheetDetail_1.setType(0);
			worksheetDetail_1.setValue("全部");
			wsDetailList.add(worksheetDetail_1);
			break;
		case 1:
			worksheetDetail_1.setType(0);
			worksheetDetail_1.setValue("全部");
			wsDetailList.add(worksheetDetail_1);
			worksheetDetail_2.setType(1);
			worksheetDetail_2.setValue("网关退款");
			wsDetailList.add(worksheetDetail_2);
			break;
		case 2:
			worksheetDetail_1.setType(0);
			worksheetDetail_1.setValue("全部");
			wsDetailList.add(worksheetDetail_1);
			worksheetDetail_2.setType(1);
			worksheetDetail_2.setValue("扣款核实订单");
			wsDetailList.add(worksheetDetail_2);
			worksheetDetail_3.setType(2);
			worksheetDetail_3.setValue("赔付订单核实");
			wsDetailList.add(worksheetDetail_3);
			worksheetDetail_4.setType(3);
			worksheetDetail_4.setValue("无法支付");
			wsDetailList.add(worksheetDetail_4);
			worksheetDetail_5.setType(4);
			worksheetDetail_5.setValue("重复支付");
			wsDetailList.add(worksheetDetail_5);
			break;
		case 3:
			worksheetDetail_1.setType(0);
			worksheetDetail_1.setValue("全部");
			wsDetailList.add(worksheetDetail_1);
			worksheetDetail_2.setType(1);
			worksheetDetail_2.setValue("查询提现问题");
			wsDetailList.add(worksheetDetail_2);
			worksheetDetail_3.setType(2);
			worksheetDetail_3.setValue("取消快捷支付");
			wsDetailList.add(worksheetDetail_3);
			worksheetDetail_4.setType(3);
			worksheetDetail_4.setValue("大额充值问题");
			wsDetailList.add(worksheetDetail_4);
			break;
		case 4:
			worksheetDetail_1.setType(0);
			worksheetDetail_1.setValue("全部");
			wsDetailList.add(worksheetDetail_1);
			worksheetDetail_2.setType(1);
			worksheetDetail_2.setValue("返现问题");
			wsDetailList.add(worksheetDetail_2);
			break;
		case 5:
			worksheetDetail_1.setType(0);
			worksheetDetail_1.setValue("全部");
			wsDetailList.add(worksheetDetail_1);
			worksheetDetail_2.setType(1);
			worksheetDetail_2.setValue("修改实名认证");
			wsDetailList.add(worksheetDetail_2);
			worksheetDetail_3.setType(2);
			worksheetDetail_3.setValue("绑卡失败");
			wsDetailList.add(worksheetDetail_3);
			break;
		case 6:
			worksheetDetail_1.setType(0);
			worksheetDetail_1.setValue("全部");
			wsDetailList.add(worksheetDetail_1);
			worksheetDetail_2.setType(1);
			worksheetDetail_2.setValue("描述不清晰");
			wsDetailList.add(worksheetDetail_2);
			worksheetDetail_3.setType(2);
			worksheetDetail_3.setValue("未发起退款");
			wsDetailList.add(worksheetDetail_3);
			worksheetDetail_4.setType(3);
			worksheetDetail_4.setValue("百度LBS自有订单");
			wsDetailList.add(worksheetDetail_4);
			worksheetDetail_5.setType(4);
			worksheetDetail_5.setValue("提供信息不全面");
			wsDetailList.add(worksheetDetail_5);
			worksheetDetail_6.setType(5);
			worksheetDetail_6.setValue("提现审核拒绝");
			wsDetailList.add(worksheetDetail_6);
			worksheetDetail_7.setType(6);
			worksheetDetail_7.setValue("支付日志已有明确支付退款信息");
			wsDetailList.add(worksheetDetail_7);
			worksheetDetail_8.setType(7);
			worksheetDetail_8.setValue("非支付中心工单");
			wsDetailList.add(worksheetDetail_8);
			worksheetDetail_9.setType(8);
			worksheetDetail_9.setValue("退款、返现等金额不符");
			wsDetailList.add(worksheetDetail_9);
			worksheetDetail_10.setType(9);
			worksheetDetail_10.setValue("重复转单");
			wsDetailList.add(worksheetDetail_10);
			break;
		case 7:
			worksheetDetail_1.setType(0);
			worksheetDetail_1.setValue("全部");
			wsDetailList.add(worksheetDetail_1);
			worksheetDetail_2.setType(1);
			worksheetDetail_2.setValue("其他");
			wsDetailList.add(worksheetDetail_2);
			break;
		default:
			worksheetDetail_1.setType(0);
			worksheetDetail_1.setValue("全部");
			wsDetailList.add(worksheetDetail_1);
			break;
		}
		return  new ResultEntity<List<WorksheetDetail>>(0, "成功", wsDetailList);
	}
	/**
	 * 文件下载
	 */
	@RequestMapping(value = "/expdownload/{expdata}", method = RequestMethod.GET)
	@ResponseBody
	public void expdownload(@PathVariable(value="expdata") String expdata,HttpServletRequest request,HttpServletResponse response){
		String fileName = "wspage" + System.currentTimeMillis() + ".xls"; // 文件名
		String sheetName = "工单报表页";// sheet名

		String[] title = new String[] { "序号", "工单号", "业务类型", "工单类型", "工单类型细分",
				"日期", "处理人", "备注" };// 标题
		//获取查询条件
		Map<String, Object> conditionMap = new HashMap<String, Object>();
		// 一、获取基本信息
		String beginDate = request.getParameter("beginDate");
		String endDate = request.getParameter("endDate");
		String worksheet_type = request.getParameter("secWsType");
		String ws_type_detail = request.getParameter("secWsDetail");
		String business_type = request.getParameter("secTradeType");
		String deal_person  = request.getParameter("secDealPerson");
		String job_num  = request.getParameter("secWsNum");
		String is_ws_commont =	request.getParameter("secIsWscommont");
		conditionMap.put("beginDate", beginDate);
		conditionMap.put("endDate", endDate);
		conditionMap.put("worksheet_type", worksheet_type);
		conditionMap.put("ws_type_detail", ws_type_detail);
		conditionMap.put("business_type", business_type);
		conditionMap.put("deal_person", deal_person);
		conditionMap.put("job_num", job_num);
		conditionMap.put("is_ws_commont", is_ws_commont);
		//查询报表数据
		List<WorksheetBaseCo> expWorksheetBaseList = worksheetCoService.getWorkSheetBoList(conditionMap);
		
		String[][] values = new String[expWorksheetBaseList.size()][];
		for (int i = 0; i < expWorksheetBaseList.size(); i++) {
			values[i] = new String[title.length];
			// 将对象内容转换成string
			WorksheetBaseCo obj = expWorksheetBaseList.get(i);
			values[i][0] = i+1 + "";
			values[i][1] = obj.getJob_num();
			values[i][2] = obj.getBusiness_type();
			values[i][3] = obj.getWorksheet_type();
			values[i][4] = obj.getWs_type_detail();
			values[i][5] = obj.getUpdate_time();
			values[i][6] = obj.getDeal_person();
			values[i][7] = obj.getWs_comment();

		}
		HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, values,
				null);
		
		// 将文件存到指定位置
		try {
			this.setResponseHeader(response, fileName);
			OutputStream os = response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 修改工单单条数据(目前仅为备注信息)
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/editsinglebase", method = RequestMethod.GET)
	@ResponseBody
	public String editSingleBase(HttpServletRequest request,
			HttpServletResponse response) {
		//获取需要修改的数据id
		String wsId = "";
		//进行删除操作
		if(request.getParameter("ws_id")!=null){
			wsId = request.getParameter("ws_id");
		}
		WorksheetBase worksheetBase = worksheetService.selectByPrimaryKey(Integer.parseInt(wsId));
		//给修改的内容进行赋值
		if(request.getParameter("ws_comment")!=null){
			worksheetBase.setWs_comment(request.getParameter("ws_comment"));
		}
		int update_result = worksheetService.updateByPrimaryKeySelective(worksheetBase);
		return update_result+"";
	}
	
	/**
	 * 删除工单单条数据
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/delsinglebase", method = RequestMethod.GET)
	@ResponseBody
	public String delSingleBase(HttpServletRequest request,
			HttpServletResponse response) {
		//获取需要删除的数据id
		String wsId = "";
		//进行删除操作
		if(request.getParameter("ws_id")!=null){
			wsId = request.getParameter("ws_id");
		}
		int delete_result = worksheetService.deleteByPrimaryKey(Integer.parseInt(wsId));
		return delete_result+"";
	}
	
	/**
	 * 批量删除工单单条数据(根据查询条件)
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/dellistbase", method = RequestMethod.GET)
	@ResponseBody
	public String delWSListBase(HttpServletRequest request,
			HttpServletResponse response) {
		//获取查询条件
		Map<String, Object> fetchSecCondition = fetchSecCondition(request);
		//进行删除操作
		int delete_result = worksheetService.deleteListByCondition(fetchSecCondition);
		return delete_result+"";
	}
	/**
	 * 工单报表电子邮件发送
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "sendemail",method = RequestMethod.GET)
	@ResponseBody
	public String sendChartEmail(HttpServletRequest request,HttpServletResponse response,HttpSession session) throws Exception{
		//获取备注信息
		String chart_comment = request.getParameter("chart_comment");
		//获取第一个图片随机数
		String random_1 = request.getParameter("random_1");
		//获取第二个图片随机数
		String random_2 = request.getParameter("random_2");
		
		worksheetCoService.sendChartEmail(chart_comment, random_1, random_2, session);
		return "success";
	}
	
	/**
	 * 
	 * @param response
	 * @param fileName
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("application/vnd.ms-excel");  
			response.setHeader("content-disposition","attachment; filename=" +fileName );
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	

	/**
	 * 获取查询报表导出数据源
	 * 
	 * @param request
	 * @return
	 */
	public List<WorksheetBase> expWorksheetBase(HttpServletRequest request) {
		Map<String, Object> fetchSecCondition = fetchSecCondition(request);
		List<WorksheetBase> selectByCondition = worksheetService
				.selectByCondition(fetchSecCondition);
		return selectByCondition;
	}

	/**
	 * 生成查询条件
	 */
	public Map<String, Object> fetchSecCondition(HttpServletRequest request) {
		Map<String, Object> conditionMap = new HashMap<String, Object>();
		conditionMap.put("beginDate", request.getParameter("beginDate"));
		conditionMap.put("endDate", request.getParameter("endDate"));
		conditionMap.put("worksheet_type", request.getParameter("secWsType"));
		conditionMap.put("ws_type_detail", request.getParameter("secWsDetail"));
		conditionMap.put("business_type", request.getParameter("secTradeType"));
		conditionMap.put("deal_person", request.getParameter("secDealPerson"));
		conditionMap.put("job_num", request.getParameter("secWsNum"));
		conditionMap.put("is_ws_commont",
				request.getParameter("secIsWscommont"));
		return conditionMap;
	}
	
	/**
	 * 生成查询条件(日报报表)
	 */
	public Map<String, Object> fetchSecChartCondition(HttpServletRequest request) {
		Map<String, Object> conditionMap = new HashMap<String, Object>();
		conditionMap.put("beginDate", request.getParameter("beginDate"));
		conditionMap.put("endDate", request.getParameter("endDate"));
		conditionMap.put("business_type", request.getParameter("secTradeType"));
		conditionMap.put("deal_person", request.getParameter("secDealPerson"));
		return conditionMap;
	}
	
	/**
	 * 
	 * @param request
	 * @return
	 * @comment 获取日报报表工单查询条件
	 */
	public HashMap<String, Object> fetchWSChartCondition(HttpServletRequest request) {

		HashMap<String, Object> conditionMap = new HashMap<String, Object>();
		//处理查询条件时间问题
		String initTim = request.getParameter("initTim");
		String beginDate = "";
		if(Integer.parseInt(initTim.split("-")[2])<15){
			if(Integer.parseInt(initTim.split("-")[1])==1){
				beginDate = (Integer.parseInt(initTim.split("-")[0])-1)+"-12-15";
			}else{
				beginDate = initTim.split("-")[0]+"-"+(Integer.parseInt(initTim.split("-")[1])-1)+"-15";
			}
		}else{
			beginDate = initTim.split("-")[0]+"-"+initTim.split("-")[1]+"-15";
		}
		conditionMap.put("initTim", initTim);
		conditionMap.put("beginDate", beginDate);
		conditionMap.put("endDate", initTim);
		conditionMap.put("worksheet_type", request.getParameter("secWsType"));
		conditionMap.put("ws_type_detail", request.getParameter("secWsDetail"));
		conditionMap.put("business_type", request.getParameter("secTradeType"));
		conditionMap.put("deal_person", request.getParameter("secDealPerson"));
		return conditionMap;
	}

	/**
	 * 
	 * @param request
	 * @return
	 * @comment 获取工单基本对象
	 */
	public WorksheetBase fetchWorksheetBase(HttpServletRequest request) {

		String job_num = request.getParameter("job_num");
		String business_type = request.getParameter("business_type");
		String worksheet_type = request.getParameter("worksheet_type");
		String ws_type_detail = request.getParameter("ws_type_detail");
		String create_time = request.getParameter("create_time");
		String deal_person = request.getParameter("deal_person");
		String wsComment = request.getParameter("ws_comment");
		WorksheetBase worksheetBase = new WorksheetBase();
		worksheetBase.setJob_num(job_num == "" ? "0" : job_num);
		worksheetBase.setBusiness_type(Integer.parseInt(business_type));
		worksheetBase.setWorksheet_type(Integer.parseInt(worksheet_type));
		worksheetBase.setWs_type_detail(ws_type_detail == "" ? "0"
				: ws_type_detail);
		// worksheetBase.create_time();
		if (""!= create_time) {
			worksheetBase.setCreate_time(QunarDateUtil.parseDate(create_time));
		}
		worksheetBase.setDeal_person(deal_person == "" ? "0" : deal_person);
		worksheetBase.setWs_comment(wsComment);
		worksheetBase.setUpdate_time(new Date());
		return worksheetBase;
	}
}
